package tech.tongyu.bob.demo.proxy.jdkproxy.proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class TransactionProxy implements InvocationHandler {
    private final Object target;

    public TransactionProxy(Object target) {
        this.target = target;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        Object result = null;
        try {
            System.out.println("开启事务...");
            // 开启事务的逻辑

            result = method.invoke(target, args); // 调用实际的业务方法

            System.out.println("提交事务...");
            // 提交事务的逻辑
        } catch (Exception e) {
            System.out.println("回滚事务...");
            // 回滚事务的逻辑
            throw e;
        }
        return result;
    }

    @SuppressWarnings("unchecked")
    public static <T> T createProxy(T target) {
        return (T) Proxy.newProxyInstance(
            target.getClass().getClassLoader(),
            target.getClass().getInterfaces(),
            new TransactionProxy(target)
        );
    }
}
